package com.itic.mall.system.synctgw.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.exports.ExportExcel;
import com.itic.appbase.applications.exports.ExportExcelWithTemplet;
import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.imports.ImportExcelUtil;
import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.EmojiHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.demo.templet.persistence.model.Templet;
import com.itic.demo.templet.persistence.model.TempletExample;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpressVo;
import com.itic.mall.system.synctgw.persistence.model.SyncTgw;
import com.itic.mall.system.synctgw.persistence.model.SyncTgwExample;
import com.itic.mall.system.synctgw.persistence.model.SyncTgwExample.Criteria;
import com.itic.mall.system.synctgw.service.SyncTgwService;
import com.itic.mall.system.marketuser.service.MarketUserService;
import com.itic.mall.system.marketuser.persistence.model.MarketUser;
import com.itic.mall.system.marketuser.persistence.model.MarketUserExample;

@Controller
@RequestMapping(value="/system/synctgw")
public class SyncTgwController
     extends BaseController {
    @Autowired
    private SyncTgwService syncTgwService;

    @Autowired
   	protected OutCommonService outCommonService;
    @Autowired
    protected MarketUserService marketUserService;
       
       //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
       private static final String MODEL_NAME_CHINA = "推广位";//中文名
       private static final String MODEL_NAME＿ENGLISH = "synctgw";//英文名
       private static final String PAGE_COMMON_PATH = "/mall/system/synctgw/synctgw";//通用路径
       private static final String COMMON_URL = "/system/synctgw/";//通用路径

       //导出常量
       private static final String TEMP = "bzmc";//备注名称
       private static final String DATALIST = "dataList";//数据常量
       //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
      
       /*
        * 主页面
        */
       @RequestMapping(value="/init")
       public String init(Model model){
        	model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
        	return PAGE_COMMON_PATH+"Main";
       }
       
       @RequestMapping(value="/initAdd")
       public String initAdd(Model model){
    	   model.addAttribute("msg", iticJsonMapper.toJson("null"));	
    	   model.addAttribute("setData", iticJsonMapper.toJson(null));
        	model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
        	return PAGE_COMMON_PATH+"Add";
       }
       /*@RequestMapping(value = "/check")
   	   @ResponseBody
       public Map<String, String> check(SyncTgw syncTgw) {
    	   Map<String, String> resultMap = new HashMap<String, String>();
   		String result = ResponseCode.SERVER_ERROR.getCode();
   		String msg = "null";
   		if(syncTgw != null){
			msg = checkIsRight(syncTgw);
			result = ResponseCode.SUCCESS.getCode();
   		}
   		resultMap.put("msg", msg);
		resultMap.put(IticConst.RESULT, result);
		return resultMap;
       }*/
       /**
        * 校验
        * @param syncTgw
        * @return
        */
	public String checkIsRight(SyncTgw syncTgw) {
		String msg = "null";
		if (syncTgw != null) {
			String tgwId = syncTgw.getTgwId();
			String userId = syncTgw.getUserId();
			if (StringHelper.isNotBlank(tgwId)) {
				SyncTgwExample example = new SyncTgwExample();
				Criteria criteria = example.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andTgwIdEqualTo(tgwId);
				List<SyncTgw> list = syncTgwService.list(example);
				if (list.size() > 0) {
					msg = "该推广位已绑定用户！";
				}
			}
			if(StringHelper.isBlank(userId)){
				/*SyncTgwExample example = new SyncTgwExample();
				Criteria criteria = example.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andUserIdEqualTo(userId);
				List<SyncTgw> list = syncTgwService.list(example);
				if (list.size() > 0) {
					msg = "该用户已有推广位！";
				}*/
				msg = "请选择一位云店主！";
			}
		}
		return msg;
	}
	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, String> add(SyncTgw syncTgw) {
		Map<String, String> resultMap = new HashMap<String, String>();
		String result = ResponseCode.SERVER_ERROR.getCode();
		String msg = "null";
		if(syncTgw != null){
			msg = checkIsRight(syncTgw);
			if(msg.equals("null")){
				String tgwId = syncTgw.getTgwId();
				String tgwName = syncTgw.getTgwName();
				String userId = syncTgw.getUserId();
				if(StringHelper.isBlank(tgwName) || StringHelper.isBlank(tgwId) || StringHelper.isBlank(userId)){
					result = ResponseCode.SUCCESS.getCode();
					msg = "请填写完整推广位ID和推广位名称和用户ID！";
				}else{
					syncTgw.setUserNickName(EmojiHelper.filterEmoji(syncTgw.getUserNickName()));
					result = syncTgwService.add(syncTgw);
				}
			}else{
				result = ResponseCode.SUCCESS.getCode();
			}
		}
		resultMap.put("msg", msg);
		resultMap.put(IticConst.RESULT, result);
		return resultMap;
	}

	@RequestMapping(value = "/initEdit")
	public String initEdit(String id,Model model) {
		if(StringHelper.isNotBlank(id)){
			SyncTgw syncTgw = syncTgwService.get(id);
			model.addAttribute("editData", iticJsonMapper.toJson(syncTgw));
			model.addAttribute("setData", iticJsonMapper.toJson(null));
			model.addAttribute("name_china", MODEL_NAME_CHINA);
			model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
			model.addAttribute("common_url", COMMON_URL);
		}else{
   			throw new ParameterErrorException();
		}
		return PAGE_COMMON_PATH + "Edit";
	}

	@RequestMapping(value = "/edit")
	@ResponseBody
	public Map<String, String> edit(SyncTgw syncTgw) {
		Map<String, String> resultMap = new HashMap<String, String>();
		String result = ResponseCode.SERVER_ERROR.getCode();
		if (syncTgw != null) {
			syncTgw.setUserNickName(EmojiHelper.filterEmoji(syncTgw.getUserNickName()));
			result = syncTgwService.edit(syncTgw);
		} else {
			throw new ParameterErrorException();
		}
		resultMap.put(IticConst.RESULT, result);
		return resultMap;
	}
	
	@RequestMapping(value = "/del")
	@ResponseBody
	public Map<String, String> del(String id) {
		Map<String, String> resultMap = new HashMap<String, String>();
		String result = ResponseCode.SERVER_ERROR.getCode();

		// 删除一个
		if (StringHelper.isNotBlank(id)) {
			SyncTgw syncTgw = new SyncTgw();
			syncTgw.setId(id);
			result = syncTgwService.delete(syncTgw);
		}else{
   			throw new ParameterErrorException();
		}

		resultMap.put(IticConst.RESULT, result);
		return resultMap;
	}
	
       @RequestMapping(value="/initImp")
       public String initImp( Model model ){
			
      		model.addAttribute("name_china", MODEL_NAME_CHINA);
          	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
          	model.addAttribute("common_url", COMMON_URL);
          	return PAGE_COMMON_PATH+"Imp";
       }
     
       
       //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
       
       /**
        * exp
        * 
        */
       @RequestMapping(value = "/exp")
       @ResponseBody
       public void exp(HttpServletRequest request, HttpServletResponse response,SyncTgw temp) {
       	 try {        	
       		    SyncTgwExample example = this.queryCondition(request,temp,null);           
                // 获取数据
                List<SyncTgw> list = syncTgwService.list(example);        
                //导出
                Map<String, Object> exportMap = new HashMap<String, Object>();
                exportMap.put(TEMP, MODEL_NAME＿ENGLISH);
                exportMap.put(DATALIST, list);
                ExportExcel exportExcel = new ExportExcelWithTemplet();
                exportExcel.exportExcel(exportMap, request, response);
                
            } catch (Exception e) {
           	 throw new RuntimeException("[TempletController | exp 模板示例导出异常]");
            } 
       }
       
       
      
       
       
       /**
        * <p>Title:queryCondition </p>
        * <p>Description:封装查询条件 </p>
        * @param jzdw
        * @param jzdwExample
        * @return
        */
       private SyncTgwExample queryCondition(HttpServletRequest request,SyncTgw temp,String code) {
       	
        	// 参数处理
    	   SyncTgwExample example = new SyncTgwExample();
           // 按创建时间倒序
           example.setOrderByClause("UPDATE_TIME DESC");
           // 按排列号顺序
           
           com.itic.mall.system.synctgw.persistence.model.SyncTgwExample.Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
           
           // 查询条件
           if ( null != temp ) {
        	   if( StringHelper.isNotBlank(temp.getUserId()) ){
        		   criteria.andUserIdLike( "%" + temp.getUserId() + "%");
        	   }
       	       if( StringHelper.isNotBlank(temp.getTgwName()) ){
       	    	   criteria.andTgwNameLike("%"+temp.getTgwName()+"%");
       	       }
       	       if( StringHelper.isNotBlank(temp.getTgwId()) ){
    	    	   criteria.andTgwIdLike("%"+temp.getTgwId()+"%");
    	       }
           }
           
           if( StringHelper.isNotBlank(code) ){
        	   MarketUser byInvitingCode = marketUserService.getByInvitingCode(code);
        	   if( null != byInvitingCode ){
        		   if( StringHelper.isNotBlank(byInvitingCode.getId()) ){
            		   criteria.andUserIdLike( "%" + byInvitingCode.getId() + "%");
            	   }
        	   }
        	   
           }
           return example;
       }
     //setStore
   	@RequestMapping(value = "/setStore")
   	public String setStore(String id, Model model) {
   		String msg = "null";
   		if (StringHelper.isNotBlank(id)) {
   			MarketUser usersMall = marketUserService.get(id);
   			//在已经创建的推广位中是否存在
   			/*SyncTgwExample example = new SyncTgwExample();
   			Criteria criteria = example.createCriteria();
   			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   			criteria.andUserIdEqualTo(id);
   			List<SyncTgw> list = syncTgwService.list(example);
   			if(list.size()>0){
   				model.addAttribute("msg", iticJsonMapper.toJson("该用户已设置过推广位！"));
   			}else{
   				model.addAttribute("msg", iticJsonMapper.toJson(msg));
   			}*/
   			model.addAttribute("msg", iticJsonMapper.toJson(msg));
			model.addAttribute("setData", iticJsonMapper.toJson(usersMall));
			model.addAttribute("name_china", MODEL_NAME_CHINA);
			model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
			model.addAttribute("common_url", COMMON_URL);
   		} else {
   			throw new ParameterErrorException();
   		}
   		return PAGE_COMMON_PATH + "Add";
   	}
       @RequestMapping(value = "/userList")
       @ResponseBody
       public Map<String, Object> userList(String userName,String flag,String uid,MarketUser marketUser, HttpServletRequest request){
           // 声明返回对象
           Map<String, Object> resultMap = new HashMap<String, Object>();
           MarketUserExample example = new MarketUserExample();
           com.itic.mall.system.marketuser.persistence.model.MarketUserExample.Criteria criteria = example.createCriteria();
           example = this.handlePageQuery(request, example);
		if (marketUser != null) {
			if(StringHelper.isNotBlank(flag)){
				if(StringHelper.isNotBlank(uid)){
					criteria.andIdEqualTo(uid);
				}
			}else{
				if (StringHelper.isNotBlank(marketUser.getId())) {
					criteria.andIdEqualTo(marketUser.getId());
				}
			}
			if (StringHelper.isNotBlank(marketUser.getUserPhone())) {
				criteria.andUserPhoneEqualTo(marketUser.getUserPhone());
			}
		}
           if(StringHelper.isNotBlank(userName)){
   			criteria.andUserNickNameEqualTo(userName);
   		}
           // 获取信息总条数
           int total = marketUserService.count(example);
           
           List<MarketUser> list = marketUserService.list(example);
           resultMap.put(IticConst.TOTAL_RECORDS, total);
           resultMap.put(IticConst.DISPLAY_RECORDS, total);
           resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
           resultMap.put(IticConst.DATA, list);
           return resultMap;
           }
       /**
        * 
        * @param goldType
        * @param request
        * @return
        */
       @RequestMapping(value = "/list")
       @ResponseBody
       public Map<String, Object> list(SyncTgw temp,String code, HttpServletRequest request){
           // 声明返回对象
           Map<String, Object> resultMap = new HashMap<String, Object>();
           
           
           SyncTgwExample example = this.queryCondition(request,temp,code);
           // 封装分页参数
           example = this.handlePageQuery(request, example);
           
           
           // 获取信息总条数
           int total = syncTgwService.count(example);
           
           // 获取数据
           List<SyncTgw> list = syncTgwService.list(example);
           
           // 数据返回处理
           resultMap.put(IticConst.TOTAL_RECORDS, total);
           resultMap.put(IticConst.DISPLAY_RECORDS, total);
           resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
           resultMap.put(IticConst.DATA, list);
           return resultMap;

       }

       
       
       /**
        * 
        * @param goldType
        * @param request
        * @return
        */
       @RequestMapping(value = "/tgws")
       @ResponseBody
       public List<SyncTgw> tgws(HttpServletRequest request){
           // 封装分页参数
           SyncTgwExample example = new SyncTgwExample();
           // 获取数据
           List<SyncTgw> list = syncTgwService.list(example);
           
           return list;

       }
       
       
       /**
        * exp
        * 
        */
       @SuppressWarnings("unchecked")
       @RequestMapping(value = "/imp")
       @ResponseBody
       public Map<String, String> imp(HttpServletRequest request,String fileId) {
       	   Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();
       	   try {
                // 获取Excel解析数据
                Map<String, Object> excelDataMap = new HashMap<String, Object>();
                String filePath = outCommonService.getFilePath(fileId);
                if (StringHelper.isNotBlank(filePath)) {
               	   excelDataMap = ImportExcelUtil.readValue( new File(FileHelper.getRootDir(), filePath), MODEL_NAME＿ENGLISH );
                }
                // 获取验证错误List集合
                List<String> errorInfoList =  (List<String>) excelDataMap.get("error");
                // 获取对象组成的List集合
                List<SyncTgw> dataList = (List<SyncTgw>) excelDataMap .get("data");                 
                if (errorInfoList != null && errorInfoList.size() > 0) {
                    // 处理错误信息，返回前台
                    result = "error";
                    resultMap.put(IticConst.DATA, "ERROR");
                    request.getSession().setAttribute("ExcelImpError",
                            errorInfoList);
                } else if (dataList != null && dataList.size() > 0) {
                    //处理excel数据
               	    result = syncTgwService.imp(dataList);
                }
            
            } catch (Exception e) {
           	   throw new RuntimeException("[SyncTgwController | imp 模板示例导入异常]");
            } 
       	     resultMap.put(IticConst.RESULT, result);
            return resultMap; 
       } 
       
       
       
       
}